import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '_views/Home'
import { isLogin } from '_utils'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: '首页',
    meta: {
      needLogin: false  //判断路由是否要登录
    },
    component: Home
  },
  {
    path: '/cate',
    name: '分类',
    meta: {
      needLogin: false
    },
    component: () => import('_views/Cate')
  },
  {
    path: '/cart',
    name: '购物车',
    meta: {
      needLogin: true  //需要登录
    },
    component: () => import('_views/Cart')
  },
  {
    path: '/user',
    name: '个人中心',
    meta: {
      needLogin: true
    },
    component: () => import('_views/User')
  },
  {
    path: '/detail/:id',/* 动态传参 */
    name: '商品详情页',
    meta: {
      needLogin: false
    },
    component: () => import('_views/Detail')
  },
  {
    path: '/itemLists',
    name: '商品列表页 ',
    meta: {
      needLogin: false
    },
    component: () => import('_views/ItemLists')
  },
  {
    path: '/login',
    meta: {
      needLogin: false
    },
    name: '登录',
    component: () => import('_views/Login')
  },
  {
    path: '/register',
    meta: {
      needLogin: false
    },
    name: '注册',
    component: () => import('_views/Register')
  },
  {
    path: '/order',
    meta: {
      needLogin: true
    },
    name: '订单页',
    component: () => import('_views/Order')
  },
  {
    path: '/contactLists',
    meta: {
      needLogin: true
    },
    name: '所有联系人',
    component: () => import('_views/ContactLists')
  },
   {
    path: '/contactAdd',
    meta: {
      needLogin: true
    },
    name: '增加联系人',
    component: () => import('_views/ContactAdd')
  },
   {
    path: '/contactUpdate',
    meta: {
      needLogin: true
    },
    name: '更新联系人',
    component: () => import('_views/ContactUpdate')
  },
  {
    path: '/search',
    meta: {
      needLogin: false
    },
    name: '搜索',
    component: () => import('_views/Search')
  },
  {
    path: '/searchLists',
    meta: {
      needLogin: false
    },
    name: '商品列表',
    component: () => import('_views/SearchLists')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
// 添加路由 全局 前置守卫
router.beforeEach((to, from, next) => {
  /*
    判断当前路由是否需要登录
      不需要则 放行
      需要 判断是否登录
        没有登录 去登录
        登录 放行
  */
  if (to.meta.needLogin) {
    // 需要登录
    if (isLogin()) {
      // 登录了放行
      next()
    } else {
      // 没有登录 传到登录页
      next({
        path: '/login',
        query: {
          from: to.path
        }
      })
    }
  } else {
    // 不需要登录
    next()
  }
})
export default router
